import cgi, md5
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from huffman import Huffman

class Handler(BaseHTTPRequestHandler):

    def do_GET(self):
        if self.path == "/":
            self.openf("inicio.html")
        if self.path == "/manual":
            self.openf("manual.html")
        if self.path == "/huffman":
            self.openf("huffman.html")
        if self.path.endswith(".png"):
            self.openi("tmp" + self.path)

    def do_POST(self):
        if self.path == "/huffman":
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
            query = cgi.parse_multipart(self.rfile, pdict)
            h = Huffman()
            text = query.get('texto')[0]
            h.read(text)
            h.sort()
            h.cod(h.data)
            h.dotpng()
            self.opent(text,h)

    def openf (self,path):
        f = open(path)
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(f.read())
        f.close()

    def openi(self,path):
        f = open(path)
        self.send_response(200)
        self.send_header('Content-type', 'image/png')
        self.end_headers()
        self.wfile.write(f.read())
        f.close()

    def opent(self,text,h):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        f = open("head.tpl")
        self.wfile.write(f.read())
        f.close()
        self.wfile.write(self.image_html(text))
        self.wfile.write(self.freq_html(h))
        self.wfile.write(self.cod_html(h))
        self.wfile.write(self.av_len_html(h))
        f = open("foot.tpl")
        self.wfile.write(f.read())
        f.close()

    def image_html(self,text):
        m = md5.new()
        m.update(text)
        return "<img src='" + m.hexdigest() + ".png' />"

    def freq_html(self,h):
        total = h.count(h.data)
        r = "<table border=1><caption>Tabla de Frecuencias</caption>"
        r += "<tr>"
        r += "<th width=50>i</th><th>Letra</th><th>Frecuencia</th><th>Cantidad</th>"         
        r += "</tr>"
        c = 1
        for i in h.freq:
            if i[1] == " ":
                j = "&nbsp;"
            else:
                j = i[1]
            r += "<tr>" + "<td>" + str(c) + "</td>"
            r += "<td>" + j + "</td>" + "<td>" + str((i[0]+.0)/total) +  "</td>"
            r += "<td align='right'>" + str(i[0]) +  "</td>" 
            r += "</tr>"
            c += 1
        r += "<tr>"
        r += "<th>&nbsp;</th><th>Total</th><th>1</th><th>" + str(total) + "</th>"         
        r += "</tr>"
        r += "</table>"
        return r

    def cod_html(self,h):
        r = "<table border=1><caption>Tabla de C&oacute;digos</caption>"
        r += "<tr>"
        r += "<th width=50>i</th><th>Letra</th><th>C&oacute;digo</th>"
        r += "</tr>"
        c = 1
        for i in h.freq:
            if i[1] == " ":
                j = "&nbsp;"
            else:
                j = i[1]
            r += "<tr>"
            r += "<td>" + str(c)  + "</td><td>" + j + "</td><td>" + h.codh[i[1]]  + "</td>"
            r += "</tr>"
            c += 1
        r += "</table>"
        return r

    def av_len_html(self,h):
        r = "<h2>Longitud Media del Mensaje</h2>"
        r += "<p>" + str(h.av_len()) + "</p>"
        return r
        
def main():
    try:
        server = HTTPServer(('', 8080), Handler)
        print 'Servidor Iniciado en el Puerto 8080'
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

if __name__ == '__main__':
    main()
